<?php

namespace App\Traits;

use Illuminate\Support\Facades\Storage;

trait ImagePath
{
    protected $defaultTemplate = 'small';

    protected $options = [
        'template' => 'small',
    ];

    /**
     * 设置缓存配置
     *
     * @param array $options
     * @return $this
     */
    public function options($options = [])
    {
        $this->options = array_merge($this->options, $options);
        return $this;
    }

    /**
     * 批量替换
     *
     * @param array $images
     * @return array
     */
    public function setImagesPath($images = [])
    {
        if (empty($images)) {
            return [];
        }
        foreach ($images as &$image) {
            $image = $this->setPath($image);
        }
        return $images;
    }

    /**
     * 根据存盘路径返回缓存路径
     *
     * @param $path
     * @return null|string|string[]
     */
    public function setPath($path)
    {
        if (empty($path) || is_array($path)) {
            return '';
        } elseif ((is_string($path) && url()->isValidUrl($path)) || strpos($path, 'data:image') === 0) {
            $src = $path;
        } else {
//            if (Storage::disk('qiniu')->exists($path)) {
            $src = Storage::disk('public')->url($path);
//            } else {
//                $src = asset($path);
//            }
        }
        return $src;
    }

    public function urlPathToCache($url, $template = null)
    {
        $template = $template ?? $this->defaultTemplate;
        return preg_replace('/(.*)(\/storage\/)(.*)/', '${1}/' . config('imagecache.route') . '/' . $template . '/${3}', $url);
    }
}